#coding=gb18030
import os
import logging
import pysvn
import argparse
import datetime

from sqlalchemy import *

def GetLogin():
    return True, 'zhoucheng', 'bbc1981', False

class SvnMonitor():
    def __init__(self, svn_path, user, password, dburl):
        self.path_list = set()
        self.svn_client  = pysvn.Client()
        self.svn_path  = svn_path
        self.user = user
        self.password  = password
        self.callback_get_login = GetLogin
        self.engine  = None
        self.new_path_insert = None
        self.path_table = None
        self.dburl  = dburl
        
    def GetLogin(self):
        return True, self.user, self.password, False

        
    def Init(self):
        selectresult = None 
        try:
            self.engine = self.engine = create_engine(self.dburl,  echo=False)
            self.path_table = self.task_t = Table('CustomScript', MetaData(self.engine), autoload = True)
            self.new_path_insert = self.path_table.insert()
            
            selectresult = self.path_table.select().execute()
            for v in selectresult.fetchall():
                self.path_list.update(v.Path)
        except Exception:
            logging.exception('load customscript table error')
            return False
        finally:
            if selectresult:
                selectresult.close()
        return True
        
    def UpdateChanger(self):
        try:
            filelist = []
            self.WalkSvnDir(filelist, self.svn_path)
            new_path_list = set([v.replace(self.svn_path, '') for v in filelist])
            
            new_add  = new_path_list - self.path_list
            old_remove = self.path_list - new_path_list
        
            for v in new_add:
                self.new_path_insert.execute(Path = v)
                self.path_list.add(v)
            
            for v in old_remove:
                self.path_table.delete(self.path_table.c.Path == v).execute()
                self.path_list.remove(v)
        except Exception:
            logging.exception('update svn path fail')
                

    def WalkSvnDir(self, file_list, svn_path):
        for v in self.svn_client.ls(svn_path):
            if v.kind == pysvn.node_kind.dir:
                self.WalkSvnDir(file_list, v.name)
            elif v.kind == pysvn.node_kind.file:
                file_list.append(v.name)
                
                
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--svn_path')
    parser.add_argument('--user')
    parser.add_argument('--password')
    parser.add_argument('--dburl')
    params = parser.parse_known_args()[0]
    
    svn_monitor = SvnMonitor(params.svn_path, params.user, params.password, params.dburl)
    
    if svn_monitor.Init() == False:
        logging.warn('init failed')
        return False
    
    timeinterval = datetime.timedelta(minuter = 1)
    last_check_time =  datetime.datetime.now()
    while True:
        now  = datetime.datetime.now()
        if now - last_check_time > timeinterval:
            svn_monitor.UpdateChanger()
            last_check_time = now
            
if __name__ == '__main__':
    main()
            